ttAutoBop = {
  autoBopEnabled : false,
  delayedVoteTimer : null,
  idleTimer : null,
  roomName : '',
  
  load : function () {
    
    //for chrome extention allowing time for room to load first
    while (!turntable || !ttObjects.getApi() || !$ || !$('ul#settings-dropdown').length)
    {
      return setTimeout("ttAutoBop.load();", 1000);
    }
	
    ttAutoBop.actions.antiIdleTime();
    ttAutoBop.views.settings.render();
    turntable.addEventListener('message', $.proxy(this.ttAutoBopMessageEvent, this));
    
    console.log('Bop-O-Matic: Loaded successfully...');
  },
  
  ttAutoBopMessageEvent : function (message) {
    if (typeof message.msgid !== 'undefined') return;
    
    //detect room changes
    if (this.roomName != $('div.name').html()) {
      this.roomName = $('div.name').html();
      ttAutoBop.actions.addManualVoteEvent();
      if(ttAutoBop.delayedVoteTimer) {
        clearTimeout(ttAutoBop.delayedVoteTimer);
        ttAutoBop.delayedVoteTimer = null;
      }
      console.log('Bop-O-Matic: Room change detected ( ' + this.roomName + ' ).');
    }
    
    switch (message.command) {
      case 'newsong':
        return ttAutoBop.actions.delayedVote();
        break;
        
      default:
        break;
    }
  }
};

ttAutoBop.views = {
  settings : {
    render : function () {
      //cleanup leftover elements on reload
      if(document.getElementById('ttAutoBopToggleElement')) {
        document.getElementById('ttAutoBopToggleElement').parentNode.removeChild(document.getElementById('ttAutoBopToggleElement'));
	  }
	  
      $('<li id="ttAutoBopToggleElement" class="option">Enable AutoBop</div>').css("color","#00FF00").click(function (e) {
        ttAutoBop.actions.toggleAutoBop();
      }).insertBefore($('ul#settings-dropdown').children().last());
    }
  }
};

ttAutoBop.actions = {
  ttObjectsInit : function  () {
    ttObjects.getApi();
    ttObjects.getManager();
  },
  
  addManualVoteEvent : function  () {
    $('div#awesome-button').on('click', function (e) {
      if(ttAutoBop.delayedVoteTimer) {
        clearTimeout(ttAutoBop.delayedVoteTimer);
        ttAutoBop.delayedVoteTimer = null;
        console.log('Bop-O-Matic: AutoBop vote canceled!');
      }
    });
  },
  
  toggleAutoBop : function  () {
    ttAutoBop.autoAwesome = !ttAutoBop.autoAwesome;
    if(ttAutoBop.autoAwesome) {
      console.log('Bop-O-Matic: Enabled!');
      ttAutoBop.autoBopEnabled = true;
      this.upVote();
      $('#ttAutoBopToggleElement').html("<b>Disable AutoBop</b>").css("color","#FF0000");
    }
    else
    {
      console.log('Bop-O-Matic: Disabled!');
      ttAutoBop.autoBopEnabled = false;
      clearTimeout(ttAutoBop.delayedVoteTimer);
      ttAutoBop.delayedVoteTimer = null;
      $('#ttAutoBopToggleElement').html("Enable AutoBop").css("color","Green");
    }
  },
  
  delayedVote : function () {
    if(ttAutoBop.delayedVoteTimer) {
      clearTimeout(ttAutoBop.delayedVoteTimer);
      ttAutoBop.delayedVoteTimer = null;
    }
    if (ttAutoBop.autoBopEnabled) {
      var t = Math.floor(Math.random() * (60000 - 10000 + 1)) + 10000; //get random time between 10 to 60 seconds
      console.log('Bop-O-Matic: Voting in ' + Math.floor(t / 1000) + ' seconds.');
      ttAutoBop.delayedVoteTimer = setTimeout(function() {
        ttAutoBop.actions.upVote();
        clearTimeout(ttAutoBop.delayedVoteTimer);
        ttAutoBop.delayedVoteTimer = null;
      }, t);
    }
  },
  
  upVote : function  () {
    this.ttObjectsInit();
    turntable.whenSocketConnected(function() {
      if (ttObjects.room.currentSong) {
        ttObjects.api({
          api: 'room.vote',
          roomid: ttObjects.room.roomId,
          val: 'up',
          vh: $.sha1(ttObjects.room.roomId + 'up' + ttObjects.room.currentSong._id),
          th: $.sha1(Math.random() + ""),
          ph: $.sha1(Math.random() + "")
        });
      }
    });
  },
  
  antiIdleTime : function () {
    clearTimeout(ttAutoBop.idleTimer);
    ttAutoBop.idleTimer = setInterval(function() {
      $($('#chat-input')[0]).keydown();
      console.log('Bop-O-Matic: Anti-idle triggered successfully.');
    }, 150000); //anti-idle triggers every 2.5 minutes
  }
};

ttObjects = {
  room : null,
  getRoom : function() {
    for (var memberName in turntable) {
      var member = turntable[memberName];
      if (typeof member !== 'object' || member === null) continue;
      if (typeof member.setupRoom !== 'undefined') {
        ttObjects.room = member;
        return member;
      }
    }
    return false;
  },

  manager : null,
  getManager : function() {
    for (var memberName in ttObjects.getRoom()) {
      var member = ttObjects.room[memberName];
      if (typeof member !== 'object' || member === null) continue;
      if (typeof member.blackswan !== 'undefined') {
        ttObjects.manager = member;
        return member;
      }
    }
    return false;
  },

  api : null,
  getApi: function () {
    var apiRegex = / Preparing message /i;
    for (var memberName in turntable) {
      var member = turntable[memberName];
      if (typeof member !== 'function') continue;
      member.toString = Function.prototype.toString;
      if (apiRegex.test(member.toString())) {
        ttObjects.api = member;
        return member;
      }
    }
    return false;
  }
};

ttAutoBop.load();